package com.zby.common.minio;

import io.minio.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Component
public class MinioFuntion {
    private static final String BUCKET_KEY = "temporary";
    private static final String BUCKET_KEY_AVATAR = "avatar";

    @Autowired
    private MinioPojo minioPojo;

    @Autowired
    private MinioClient minioClient;


    //    桶权限设置
    private String createBucketPolicyConfig(String bucketName) {

        return """
                {
                  "Statement" : [ {
                    "Action" : "s3:GetObject",
                    "Effect" : "Allow",
                    "Principal" : "*",
                    "Resource" : "arn:aws:s3:::%s/*"
                  } ],
                  "Version" : "2012-10-17"
                }
                """.formatted(bucketName);
    }

    //    删除文件
    public void deleteFile(String fileName) throws Exception {
        minioClient.removeObject(RemoveObjectArgs.builder()
                .bucket(getBucketName(BUCKET_KEY))
                .object(fileName)
                .build());
    }

    //    检测桶是否存在
    public void ensureBucketExists(String bucketKey) throws Exception {
        String bucketName = getBucketName(bucketKey);
        if (!minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build())) {
            minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
            setBucketPolicy(bucketName);
        }
    }
    // 设置桶权限

    public void setBucketPolicy(String bucketName) throws Exception {
        minioClient.setBucketPolicy(SetBucketPolicyArgs.builder().bucket(bucketName).config(createBucketPolicyConfig(bucketName)).build());
    }

    //    获取桶名
    public String getBucketName(String bucketKey) {
        return minioPojo.getBuckets().get(bucketKey).getBucketName();
    }

    // 复制文件
    // 在UploadFileServiceImp中添加方法
    public String transferBetweenBuckets(String sourceBucketKey, String targetBucketKey, String objectName) throws Exception {
//        判空
        if (sourceBucketKey == null || targetBucketKey == null || objectName == null) {
            return null;
        }
        // 获取桶配置
        String sourceBucket = getBucketName(sourceBucketKey);
        String targetBucket = getBucketName(targetBucketKey);
        ensureBucketExists(targetBucketKey);

        // 生成新文件名（可选）
        String newFileName = generateNewName(objectName);

        // 执行服务端复制（无需下载上传）
        minioClient.copyObject(CopyObjectArgs.builder()
                .source(CopySource.builder()
                        .bucket(sourceBucket)
                        .object(objectName)
                        .build())
                .bucket(targetBucket)
                .object(newFileName)
                .build());

        // 返回新文件地址
        return String.join("/", minioPojo.getEndpoint(), getBucketName(BUCKET_KEY_AVATAR), newFileName);
    }

    private String generateNewName(String originalName) {

      return   new SimpleDateFormat("yyyyMMdd")
                .format(new Date()) + "/" + UUID.randomUUID() + "-" + originalName;

    }

}

